package com.lt.test.consumer.web.exceptionresolver;

import com.lt.test.common.constant.HttpRequestConstant;
import com.lt.test.common.exception.CustomException;
import com.lt.test.entity.DTO.ResponseDTO;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by zhengchuan on 2017/4/6.
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(CustomExceptionResolver.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error("全局异常处理："+ex.getMessage());
        ex.printStackTrace();
        CustomException customException = null;
        if(ex instanceof CustomException){
            customException = (CustomException)ex;
        } else if (ex instanceof UnauthorizedException) {
            customException  = new CustomException("权限不够");
        } else{
            customException = new CustomException("未知错误");
        }

        //错误信息
        String message = customException.getMessage();
        ModelAndView modelAndView = new ModelAndView();

        //区分是ajax请求还是普通请求
        String hande = request.getHeader("x-requested-with");   //XMLHttpRequest为ajax请求，null为正常请求
        if (hande != null && hande.equalsIgnoreCase("XMLHttpRequest")){//ajax请求
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            ResponseDTO result = new ResponseDTO();
            result.setCode(HttpRequestConstant.SERVER_ERROR_CODE);
            result.setMessage(message);
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();

            }

            String json = JSONObject.fromObject(result).toString();
            out.write(json);
            out.flush();
            out.close();
            return modelAndView;
        }
        //将错误信息传到页面
        modelAndView.addObject("message", message);

        //指向错误页面
        modelAndView.setViewName("content/error-500");
        return modelAndView;
    }
}
